<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search_val" placeholder="搜索订单" style="width: 400px;margin-right: 10px;" @keyup.enter.native="handleFilter">
        <el-select slot="prepend" v-model="listQuery.search_key" placeholder="请选择">
          <template v-for="item in searchKeys">
            <el-option v-if="!(item.val === 'num' && listQuery.type === 'send')" :key="item.val" :label="item.label" :value="item.val" />
          </template>
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
    >
      <el-table-column align="center" label="ID" width="60" prop="id" />
      <el-table-column align="center" label="订单编号" width="140" prop="order_number" />
      <el-table-column align="center" label="订单总额" width="120" prop="price" />
      <el-table-column align="center" label="拍品数量" width="80">
        <template slot-scope="scope">{{ scope.row.goods.length }}</template>
      </el-table-column>
      <el-table-column align="center" label="姓名" width="90" prop="user_name" />
      <el-table-column align="center" label="号牌" width="90" prop="user_num" />
      <el-table-column align="center" label="备注" width="230" prop="remark" show-overflow-tooltip />
      <el-table-column align="center" label="订单状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="statusMap[scope.row.status].tag">{{ statusMap[scope.row.status].text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="120" prop="create_time" />
      <el-table-column fixed="right" align="center" label="订单详情" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" style="font-size: 14px" @click="handleDetail(scope.row, 'edit')">查看/修改</el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="230">
        <template slot-scope="scope">
          <el-button-group>
            <el-button v-if="scope.row.status === 0" size="mini" type="warning" @click="handleDetail(scope.row, 'pay')">
              {{ scope.row.type === 'send' ? '结算' : '付款' }}
            </el-button>
            <el-button v-if="scope.row.status === 0" size="mini" type="danger" @click="handleDetail(scope.row, 'void')">作废</el-button>
            <el-button size="mini" type="primary" @click="handlePrint(scope.row)">
              {{ scope.row.type === 'send' ? '结算单' : '付款提货单' }}
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="total > 0" class="pagination-container">
      <el-pagination background :current-page="listQuery.page" :page-sizes="[15, 20, 30]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog title="订单详情" width="60%" :visible.sync="dialogOrderVisible">
      <order-table v-if="currOrder" ref="order-table" :type="routeName === 'OrderSend' ? 'send' : 'buy'" :goods-list="currOrder.goods" />
      <br><br>
      <el-form v-if="currOrder && currOrder.orderForm" :model="currOrder.orderForm" label-position="left" label-width="80px">
        <el-form-item label="其他费用">
          <el-input v-model.trim="currOrder.orderForm.other_fee" :disabled="currOrder && currOrder.status === 1" />
        </el-form-item>
        <el-form-item label="合计费用">
          <el-input v-model="orderTotalFee" type="number" disabled />
        </el-form-item>
        <el-form-item label="转账银行">
          <el-input v-model.trim="currOrder.orderForm.bankname" :disabled="currOrder && currOrder.status === 1" />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model.trim="currOrder.orderForm.bankcard" :disabled="currOrder && currOrder.status === 1" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model.trim="currOrder.orderForm.address" :disabled="currOrder && currOrder.status === 1" type="textarea" :autosize="{ minRows: 1, maxRows: 2}" />
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model.trim="currOrder.orderForm.remark" :disabled="currOrder && currOrder.status === 1" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="currOrder && currOrder.status === 1" @click="dialogOrderVisible = false">关 闭</el-button>
        <template v-else>
          <el-button @click="dialogOrderVisible = false">取 消</el-button>
          <el-button :loading="updateLoading" :type="dialogOrderBtn === 'void' ? 'danger' : 'primary'" @click="handleUpdate">
            {{ btnMap[dialogOrderBtn] }}
          </el-button>
        </template>
      </div>
    </el-dialog>

    <el-dialog class="print-dialog" fullscreen center :visible.sync="dialogPrintVisible">
      <div id="printContent">
        <print-table :title="printData.title" :type="printData.type" :info="printData.info" :list="printData.list" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClosePrint">关 闭</el-button>
        <el-button :loading="printLoading" type="primary" @click="doPrint">打 印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Print from 'print-js'
// import { toThousands } from '@/utils'
import PrintTable from './components/PrintTable'
import OrderTable from './components/OrderTable'
import { getOrders, updateOrder } from '@/api/order'

export default {
  components: { PrintTable, OrderTable },
  data () {
    return {
      listQuery: {
        page: 1,
        limit: 15,
        type: '',
        search_key: 'user_name',
        search_val: ''
      },
      searchKeys: [
        { label: '订单号', val: 'order_number' },
        { label: '姓名', val: 'user_name' }
      ],
      list: null,
      listLoading: true,
      total: 0,
      routeName: this.$route.name,
      statusMap: {
        '-1': { text: '作废', tag: 'info' },
        0: { text: '待付款', tag: 'danger' },
        1: { text: '已完成', tag: 'success' }
      },
      btnMap: {
        'edit': '更新订单',
        'pay': '确认' + (this.$route.name === 'OrderSend' ? '结算' : '付款'),
        'void': '确认作废'
      },
      dialogOrderVisible: false,
      dialogOrderBtn: '',
      updateLoading: false,
      currOrder: null,
      dialogPrintVisible: false,
      printLoading: false,
      printData: {
        type: '',
        title: '',
        info: {},
        list: []
      },
      jumpPrint: false
    }
  },
  computed: {
    // 其他费用+合计
    orderTotalFee () {
      const sumarr = this.currOrder.goods.map(el => el.sum)
      var sum = 0
      if (sumarr.length > 0) {
        sum = sumarr.reduce(function (prev, curr, idx, arr) {
          return Number(prev) + Number(curr)
        })
        if (this.currOrder.orderForm.other_fee >= 0) {
          sum += Number(this.currOrder.orderForm.other_fee)
        } else if (this.currOrder.orderForm.other_fee < 0) {
          sum -= Math.abs(this.currOrder.orderForm.other_fee)
        } else {
          sum = sum + 0
        }
      } else {
        sum = this.currOrder.orderForm.other_fee
      }
      return sum
    }
  },
  created () {
    this.listQuery.type = this.$route.name === 'OrderBuy' ? 'buy' : 'send'
    if (this.$route.query.order) {
      this.listQuery.search_key = 'order_number'
      this.listQuery.search_val = this.$route.query.order
    }
    if (this.$route.query.order && this.$route.query.print) {
      this.jumpPrint = true
    }
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.listLoading = true
      getOrders(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
        if (this.jumpPrint) {
          this.handlePrint(this.list[0])
        }
      }).catch(err => {
        this.listLoading = false
        console.log(err)
      })
    },
    handleDetail (row, btn) {
      this.dialogOrderBtn = btn
      var curr = JSON.parse(JSON.stringify(row))
      curr.orderForm = {
        other_fee: curr.other_fee,
        bankname: curr.bankname,
        bankcard: curr.bankcard,
        address: curr.address,
        remark: curr.remark
      }
      this.currOrder = curr
      this.dialogOrderVisible = true
    },

    handleUpdate () {
      this.updateLoading = true
      const data = this.currOrder.orderForm
      data.id = this.currOrder.id
      data.status = this.currOrder.status
      if (this.dialogOrderBtn === 'pay') {
        data.status = 1
      } else if (this.dialogOrderBtn === 'void') {
        data.status = -1
      }
      updateOrder(data).then(res => {
        this.updateLoading = false
        this.fetchData()
        this.dialogOrderVisible = false
        this.$message.success(res.msg)
      }).catch(err => {
        console.log(err)
        this.updateLoading = false
      })
    },

    handlePrint (row) {
      var curr = JSON.parse(JSON.stringify(row))
      this.currOrder = curr
      this.printData.info = {
        lotId: this.currOrder.lotId,
        lotName: this.currOrder.lotName,
        user_name: this.currOrder.user_name,
        bankname: this.currOrder.bankname,
        bankcard: this.currOrder.bankcard,
        address: this.currOrder.address,
        user_num: this.currOrder.user_num,
        order_number: this.currOrder.order_number
      }
      if (this.routeName === 'OrderBuy') {
        this.printData.title = '付款提货单'
        this.printData.type = 'settle_buy'
        this.printData.info.other_fee = this.currOrder.other_fee
        this.printData.info.lot_rate = this.currOrder.lot_rate
        this.printData.info.price = this.currOrder.price
        this.printData.info.price_rmb = this.currOrder.price_rmb
      } else {
        this.printData.title = '出品人结算单'
        this.printData.type = 'settle_send'
      }
      this.printData.list = this.currOrder.goods
      this.dialogPrintVisible = true
    },
    handleClosePrint () {
      this.dialogPrintVisible = false
      this.jumpPrint = false
      this.$router.replace(`/order/${this.listQuery.type}?order=${this.listQuery.search_val}`)
    },
    doPrint () {
      const style = '@page { margin:0 } '
      Print({
        printable: 'printContent',
        type: 'html',
        style: style,
        // 继承原来的所有样式
        targetStyles: ['*']
      })
      this.jumpPrint = false
      this.$router.replace(`/order/${this.listQuery.type}?order=${this.listQuery.search_val}`)
    },
    handleFilter () {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.fetchData()
    }
  }
}
</script>
<style lang="scss" scoped>
.el-table {
  width: fit-content;
  margin-bottom: 20px;
}
.print-dialog {
  /deep/.el-dialog__body {
    padding: 0 calc(50vw - 405px);
    height: calc(100vh - 120px);
    overflow: scroll;
  }
}
</style>
<style lang="scss">
#printContent {
  width: 790px;
  padding: 20px;
  margin: auto;
  .el-table--medium td {
    padding: 8px 0;
    font-size: 13px;
    .cell {
      padding: 0 4px;
    }
  }
}
</style>
